package org.example.test;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

import static java.lang.Thread.sleep;

public class CountDownLatchTest1 {
    public static void main(String[] args) {
        CountDownLatch latchWhenThreadBAfter4Step = new CountDownLatch(1);
        CountDownLatch latchWhenThreadAAfter5Step = new CountDownLatch(1);


        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread-1:step1");

                randomSleep();

                System.out.println("Thread-1:step2");

                randomSleep();

                System.out.println("Thread-1:step3");

                try {
                    latchWhenThreadBAfter4Step.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

                System.out.println("Thread-1:step4");

                randomSleep();

                System.out.println("Thread-1:step5");

                latchWhenThreadAAfter5Step.countDown();
            }
        }, "Thread-1").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Thread-2:step1");

                randomSleep();

                System.out.println("Thread-2:step2");

                randomSleep();

                System.out.println("Thread-2:step3");

                randomSleep();

                System.out.println("Thread-2:step4");

                latchWhenThreadBAfter4Step.countDown();

                try {
                    latchWhenThreadAAfter5Step.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("Thread-2:step5");
            }
        }, "Thread-2").start();
    }

    private static void randomSleep() {
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

